/**
 * 需求管理相关API接口
 */
import { request } from '@/utils/request'
import type { ApiResponse } from '@/types/api'
import type { StateOption } from '@/types/state'
import type { AxiosResponse } from 'axios'

// 需求状态通过状态管理系统动态获取
// 使用 useRequirementStates composable 获取状态选项
export type RequirementStatus = string

// 需求优先级枚举
export enum RequirementPriority {
  LOW = 'low',          // 低
  MEDIUM = 'medium',    // 中
  HIGH = 'high',        // 高
  CRITICAL = 'critical', // 严重
  URGENT = "URGENT"
}

// 需求类型枚举
export enum RequirementType {
  FUNCTIONAL = 'functional',           // 功能性需求
  NON_FUNCTIONAL = 'non_functional',   // 非功能性需求
  BUSINESS = 'business',               // 业务需求
  TECHNICAL = 'technical',             // 技术需求
  INTERFACE = 'interface',             // 接口需求
  PERFORMANCE = 'performance',         // 性能需求
  SECURITY = 'security',               // 安全需求
  USABILITY = 'usability'              // 可用性需求
}

// 需求来源枚举
export enum RequirementSource {
  CUSTOMER = 'customer',               // 客户
  STAKEHOLDER = 'stakeholder',         // 利益相关者
  MARKET_RESEARCH = 'market_research', // 市场调研
  COMPETITOR = 'competitor',           // 竞争对手
  INTERNAL = 'internal',               // 内部
  REGULATION = 'regulation',           // 法规要求
  TECHNICAL_DEBT = 'technical_debt'    // 技术债务
}

// 需求评论接口
export interface RequirementComment {
  id: string
  user_id: string
  user_name: string
  content: string
  parent_id?: string
  is_deleted?: boolean
  created_at: string
  updated_at?: string
  deleted_at?: string
  replies?: RequirementComment[]
}

// 需求附件接口
export interface RequirementAttachment {
  id: string
  filename: string
  original_filename: string
  file_size: number
  file_type: string
  url: string
  uploaded_by: string
  uploaded_at: string
}

// 需求依赖关系接口
export interface RequirementDependency {
  requirement_id: string
  dependency_type: string // blocks, depends_on, relates_to
  description?: string
}

// 需求基础接口
export interface RequirementBase {
  title: string
  description?: string
  requirement_type: RequirementType
  status: RequirementStatus
  priority: RequirementPriority
  source: RequirementSource
  project_id: string
  assignee_id?: string | null
  reporter_id: string
  acceptance_criteria?: string
  business_value?: string
  estimated_effort?: number
  actual_effort?: number
  start_date?: string
  due_date?: string
  tags: string[]
  parent_id?: string
}

// 需求创建接口
export interface RequirementCreate extends RequirementBase {}

// 需求更新接口
export interface RequirementUpdate {
  title?: string
  description?: string
  requirement_type?: RequirementType
  status?: RequirementStatus
  priority?: RequirementPriority
  source?: RequirementSource
  assignee_id?: string | null
  project_id?: string
  reporter_id?: string | null
  acceptance_criteria?: string
  business_value?: string
  estimated_effort?: number
  actual_effort?: number
  start_date?: string | null
  due_date?: string | null
  tags?: string[]
  parent_id?: string | null
}

// 需求响应接口
export interface RequirementResponse {
  id: string
  title: string
  description?: string
  requirement_type: RequirementType
  status: RequirementStatus
  priority: RequirementPriority
  source: RequirementSource
  project_id: string
  project_name?: string
  assignee_id?: string | null
  assignee_name?: string
  reporter_id: string
  reporter_name?: string
  updated_by_id?: string | null
  updated_by_name?: string
  acceptance_criteria?: string
  business_value?: string
  estimated_effort?: number
  actual_effort?: number
  start_date?: string
  due_date?: string
  tags: string[]
  comments: RequirementComment[]
  attachments: RequirementAttachment[]
  dependencies: RequirementDependency[]
  watchers: string[]
  versions?: Array<{
    id: string
    name: string
    version_number?: string
    status?: string
    release_date?: string
  }>
  created_at: string
  updated_at: string
  approved_at?: string
  implemented_at?: string
  is_overdue?: boolean
  progress?: number
  related_tasks_count?: number
  completed_tasks_count?: number
  related_defects_count?: number
  resolved_defects_count?: number
  parent_id?: string | null
  parent_name?: string
  children_count?: number
}

// 需求摘要接口
export interface RequirementSummary {
  id: string
  title: string
  status: RequirementStatus
  priority: RequirementPriority
  assignee_name?: string
  due_date?: string
  is_overdue: boolean
  progress: number
}

// 需求管理接口
export interface RequirementBoard {
  project_id: string
  project_name: string
  columns: Record<string, RequirementSummary[]>
}

// 需求列接口
export interface RequirementBoardColumn {
  status: RequirementStatus
  title: string
  requirements: RequirementSummary[]
  requirement_count: number
}



// 需求筛选接口
export interface RequirementFilter {
  status?: RequirementStatus[]
  priority?: RequirementPriority[]
  requirement_type?: RequirementType[]
  source?: RequirementSource[]
  assignee_id?: string
  reporter_id?: string
  project_id?: string
  tags?: string[]
  due_date_range?: { start: string; end: string }
  created_date_range?: { start: string; end: string }
  is_overdue?: boolean
}

// 需求评论创建接口
export interface RequirementCommentCreate {
  content: string
  parent_id?: string
}

// 需求评论更新接口
export interface RequirementCommentUpdate {
  content: string
}

// 需求状态更新接口
export interface RequirementStatusUpdate {
  status: RequirementStatus
  comment?: string
}

// 需求分配更新接口
export interface RequirementAssignmentUpdate {
  assignee_id?: string | null
  comment?: string
}

// 需求批量更新接口
export interface RequirementBulkUpdate {
  requirement_ids: string[]
  updates: RequirementUpdate
}

// 需求查询参数接口
export interface RequirementQueryParams {
  version_id?: string
  skip?: number
  limit?: number
  page?: number
  size?: number
  search?: string
  project_id?: string
  assignee_id?: string
  reporter_id?: string
  status?: RequirementStatus
  priority?: RequirementPriority
  requirement_type?: RequirementType
  source?: RequirementSource
  due_date_start?: string
  due_date_end?: string
  tags?: string
  version?: string
  sort_by?: string
  sort_order?: 'asc' | 'desc'
  created_at_start?: string
  created_at_end?: string
  has_version?: boolean
  parent_id?: string
}

// 需求计数查询参数接口
export interface RequirementCountParams {
  search?: string
  project_id?: string
  assignee_id?: string
  reporter_id?: string
  status?: RequirementStatus
  priority?: RequirementPriority
  requirement_type?: RequirementType
  source?: RequirementSource
  due_date_start?: string
  due_date_end?: string
  tags?: string
  version?: string
  created_at_start?: string
  created_at_end?: string
  has_version?: boolean
}

/**
 * 处理API响应，统一转换为ApiResponse格式
 */
function handleApiResponse<T>(response: any, defaultData: T): ApiResponse<T> {
  if (response.data && response.data.success) {
    return {
      status: response.status,
      statusText: response.statusText,
      success: response.data.success,
      code: response.data.code,
      message: response.data.message,
      data: response.data.data || defaultData,
      pagination: response.data.pagination,
      timestamp: new Date().toISOString()
    }
  }
  // 确保始终返回ApiResponse格式
  return {
    status: response.status || 500,
    statusText: response.statusText || 'Internal Server Error',
    success: false,
    code: response.data?.code || 500,
    message: response.data?.message || '请求失败',
    data: defaultData,
    timestamp: new Date().toISOString()
  }
}

/**
 * 获取需求列表
 */
export const getRequirements = (params?: RequirementQueryParams): Promise<ApiResponse<RequirementResponse[]>> => {
  return request.get('/requirements/', { params })
    .then(response => {
      // 后端使用paginated_response返回格式：{success: true, data: [...], pagination: {...}}
      const result = handleApiResponse(response, [] as RequirementResponse[])
      // 特殊处理：确保data是数组
      if (!Array.isArray(result.data)) {
        result.data = []
      }
      return result
    })
    .catch(error => {
      console.error('获取需求列表失败:', error)
      // 返回错误响应格式
      return {
        success: false,
        status: error?.response?.status || 500,
        statusText: error?.response?.statusText || 'Internal Server Error',
        code: error?.response?.data?.code || 500,
        message: error?.response?.data?.message || error?.message || '获取需求列表失败',
        data: [] as RequirementResponse[],
        timestamp: new Date().toISOString()
      } as ApiResponse<RequirementResponse[]>
    })
}

/**
 * 获取需求总数
 */
export const getRequirementsCount = (params?: RequirementCountParams): Promise<ApiResponse<{ count: number }>> => {
  return request.get('/requirements/count', { params }).then(response => 
    handleApiResponse(response, { count: 0 })
  )
}

/**
 * 根据ID获取需求详情
 */
export const getRequirementById = (id: string): Promise<ApiResponse<RequirementResponse>> => {
  // 验证ID有效性
  if (!id || id === 'undefined' || id === 'null' || id.trim() === '') {
    return Promise.reject(new Error('无效的需求ID'))
  }
  
  return request.get(`/requirements/${id}`)
    .then(response => handleApiResponse(response, {} as RequirementResponse))
    .catch(error => {
      console.error('获取需求详情失败:', error)
      // 如果是404，返回友好的错误消息
      if (error?.response?.status === 404) {
        throw new Error('需求不存在或已被删除')
      }
      throw error
    })
}

/**
 * 创建需求
 */
export const createRequirement = (data: RequirementCreate): Promise<ApiResponse<RequirementResponse>> => {
  // 验证必需字段
  if (!data || typeof data !== 'object') {
    return Promise.reject(new Error('需求数据无效'))
  }
  if (!data.title || !data.title.trim()) {
    return Promise.reject(new Error('需求标题是必填字段'))
  }
  if (!data.project_id || data.project_id.trim() === '') {
    return Promise.reject(new Error('所属项目是必填字段'))
  }
  if (!data.reporter_id || data.reporter_id.trim() === '') {
    return Promise.reject(new Error('报告人是必填字段'))
  }
  
  return request.post('/requirements/', data)
    .then(response => handleApiResponse(response, {} as RequirementResponse))
    .catch(error => {
      console.error('创建需求失败:', error)
      // 处理验证错误
      if (error?.response?.status === 422) {
        const validationErrors = error?.response?.data?.detail || []
        const errorMessages = validationErrors.map((err: { msg?: string; loc?: string[] }) => 
          err.msg || '验证失败'
        ).join('; ')
        throw new Error(errorMessages || '数据验证失败，请检查输入')
      }
      throw error
    })
}

/**
 * 更新需求
 */
export const updateRequirement = (id: string, data: RequirementUpdate): Promise<ApiResponse<RequirementResponse>> => {
  // 验证参数
  if (!id || id.trim() === '') {
    return Promise.reject(new Error('需求ID无效'))
  }
  if (!data || typeof data !== 'object') {
    return Promise.reject(new Error('更新数据无效'))
  }
  
  return request.put(`/requirements/${id}`, data)
    .then(response => handleApiResponse(response, {} as RequirementResponse))
    .catch(error => {
      console.error('更新需求失败:', error)
      // 处理404错误
      if (error?.response?.status === 404) {
        throw new Error('需求不存在或已被删除')
      }
      // 处理验证错误
      if (error?.response?.status === 422) {
        const validationErrors = error?.response?.data?.detail || []
        const errorMessages = validationErrors.map((err: { msg?: string }) => 
          err.msg || '验证失败'
        ).join('; ')
        throw new Error(errorMessages || '数据验证失败，请检查输入')
      }
      throw error
    })
}

/**
 * 删除需求
 */
export const deleteRequirement = (id: string): Promise<ApiResponse<void>> => {
  // 验证ID有效性
  if (!id || id.trim() === '') {
    return Promise.reject(new Error('需求ID无效'))
  }
  
  return request.delete(`/requirements/${id}`)
    .then(response => {
      // 处理统一响应格式 - 删除操作通常只需要检查成功状态
      if (response.data && response.data.success === false) {
        throw new Error(response.data.message || '删除需求失败')
      }
      return handleApiResponse(response, undefined as void)
    })
    .catch(error => {
      console.error('删除需求失败:', error)
      // 处理404错误
      if (error?.response?.status === 404) {
        throw new Error('需求不存在或已被删除')
      }
      // 处理权限错误
      if (error?.response?.status === 403) {
        throw new Error('您没有权限删除此需求')
      }
      throw error
    })
}

/**
 * 批量删除需求
 */
export const batchDeleteRequirements = (ids: string[]): Promise<ApiResponse<void>> => {
  return request.delete('/requirements/bulk', { data: { requirement_ids: ids } }).then(response => {
    if (response.data && response.data.success === false) {
      throw new Error(response.data.message || '批量删除需求失败')
    }
    return handleApiResponse(response, undefined as void)
  })
}

/**
 * 更新需求状态
 */
export const updateRequirementStatus = (id: string, data: RequirementStatusUpdate): Promise<ApiResponse<RequirementResponse>> => {
  return request.patch(`/requirements/${id}/status`, data).then(response => 
    handleApiResponse(response, {} as RequirementResponse)
  )
}

/**
 * 更新需求分配
 */
export const updateRequirementAssignee = (id: string, data: RequirementAssignmentUpdate): Promise<ApiResponse<RequirementResponse>> => {
  return request.put(`/requirements/${id}/assignee`, data).then(response => 
    handleApiResponse(response, {} as RequirementResponse)
  )
}

/**
 * 批量更新需求
 */
export const batchUpdateRequirements = (data: RequirementBulkUpdate): Promise<ApiResponse<RequirementResponse[]>> => {
  return request.post('/requirements/bulk', data).then(response => 
    handleApiResponse(response, [] as RequirementResponse[])
  )
}

/**
 * 获取需求评论
 */
export const getRequirementComments = (id: string): Promise<ApiResponse<RequirementComment[]>> => {
  return request.get(`/requirements/${id}/comments`).then(response => 
    handleApiResponse(response, [] as RequirementComment[])
  )
}

/**
 * 添加需求评论
 */
export const addRequirementComment = (id: string, data: RequirementCommentCreate): Promise<ApiResponse<RequirementComment>> => {
  return request.post(`/requirements/${id}/comments`, data).then(response => 
    handleApiResponse(response, {} as RequirementComment)
  )
}

/**
 * 更新需求评论
 */
export const updateRequirementComment = (id: string, commentId: string, data: RequirementCommentUpdate): Promise<ApiResponse<RequirementComment>> => {
  return request.put(`/requirements/${id}/comments/${commentId}`, data).then(response => 
    handleApiResponse(response, {} as RequirementComment)
  )
}

/**
 * 删除需求评论
 */
export const deleteRequirementComment = (id: string, commentId: string): Promise<ApiResponse<void>> => {
  return request.delete(`/requirements/${id}/comments/${commentId}`).then(response => {
    if (response.data && response.data.success === false) {
      throw new Error(response.data.message || '删除需求评论失败')
    }
    return handleApiResponse(response, undefined as void)
  })
}

/**
 * 获取需求附件
 */
export const getRequirementAttachments = (id: string): Promise<ApiResponse<RequirementAttachment[]>> => {
  return request.get(`/requirements/${id}/attachments`).then(response => 
    handleApiResponse(response, [] as RequirementAttachment[])
  )
}

/**
 * 上传需求附件
 */
export const uploadRequirementAttachment = (id: string, file: File): Promise<ApiResponse<RequirementAttachment>> => {
  const formData = new FormData()
  formData.append('file', file)
  
  return request.post(`/requirements/${id}/attachments`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(response => 
    handleApiResponse(response, {} as RequirementAttachment)
  )
}

/**
 * 下载需求附件
 */
export const downloadRequirementAttachment = (id: string, attachmentId: string) => {
  return request.get(`/requirements/${id}/attachments/${attachmentId}/download`, {
    responseType: 'blob'
  })
}

/**
 * 删除需求附件
 */
export const deleteRequirementAttachment = (id: string, attachmentId: string): Promise<ApiResponse<void>> => {
  return request.delete(`/requirements/${id}/attachments/${attachmentId}`).then(response => {
    if (response.data && response.data.success === false) {
      throw new Error(response.data.message || '删除需求附件失败')
    }
    return handleApiResponse(response, undefined as void)
  })
}

/**
 * 导出需求数据
 */
export const exportRequirements = (params?: RequirementQueryParams): Promise<AxiosResponse<Blob>> => {
  return request.get('/requirements/export', { 
    params,
    responseType: 'blob'
  })
}

/**
 * 导入需求数据
 */
export const importRequirements = (file: File): Promise<ApiResponse<{ success_count: number; error_count: number; errors: string[] }>> => {
  const formData = new FormData()
  formData.append('file', file)
  
  return request.post('/requirements/import', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(response => 
    handleApiResponse(response, { success_count: 0, error_count: 0, errors: [] })
  )
}

/**
 * 下载需求导入模板
 */
export const downloadRequirementTemplate = (): Promise<AxiosResponse<Blob>> => {
  return request.get('/requirements/export-template', {
    responseType: 'blob'
  })
}

// 需求状态选项 - 将由动态状态管理器提供
export const requirementStatusOptions: StateOption[] = []

// 需求优先级选项 - 将由动态状态管理器提供  
export const requirementPriorityOptions: StateOption[] = []

// 需求类型选项
export const requirementTypeOptions = [
  { label: '功能性需求', value: RequirementType.FUNCTIONAL },
  { label: '非功能性需求', value: RequirementType.NON_FUNCTIONAL },
  { label: '业务需求', value: RequirementType.BUSINESS },
  { label: '技术需求', value: RequirementType.TECHNICAL },
  { label: '接口需求', value: RequirementType.INTERFACE },
  { label: '性能需求', value: RequirementType.PERFORMANCE },
  { label: '安全需求', value: RequirementType.SECURITY },
  { label: '可用性需求', value: RequirementType.USABILITY }
]

// 需求来源选项
export const requirementSourceOptions = [
  { label: '客户', value: RequirementSource.CUSTOMER },
  { label: '利益相关者', value: RequirementSource.STAKEHOLDER },
  { label: '市场调研', value: RequirementSource.MARKET_RESEARCH },
  { label: '竞争对手', value: RequirementSource.COMPETITOR },
  { label: '内部', value: RequirementSource.INTERNAL },
  { label: '法规要求', value: RequirementSource.REGULATION },
  { label: '技术债务', value: RequirementSource.TECHNICAL_DEBT }
]

// RequirementItem 类型别名，用于组件中
export type RequirementItem = RequirementResponse

// RequirementAPI 对象 - 统一管理所有需求相关API（向后兼容）
export const requirementAPI = {
  /**
   * 获取需求列表
   */
  async getRequirements(params?: RequirementQueryParams): Promise<{
    items: RequirementResponse[]
    total: number
    page: number
    size: number
  }> {
    const response = await getRequirements(params)
    
    if (response.success && response.data) {
      const pagination = (response as any).pagination
      
      // 情况1: data是数组，pagination在响应对象上（后端paginated_response的标准格式）
      if (Array.isArray(response.data)) {
        return {
          items: response.data,
          total: pagination?.total || response.data.length,
          page: pagination?.page || (params?.skip ? Math.floor(params.skip / (params.limit || 20)) + 1 : 1),
          size: pagination?.size || (params?.limit || 20)
        }
      }
      
      // 情况2: data是对象，包含items和pagination
      const dataObj = response.data as any
      if (dataObj.items && Array.isArray(dataObj.items)) {
        return {
          items: dataObj.items,
          total: dataObj.total || dataObj.pagination?.total || dataObj.items.length,
          page: dataObj.page || dataObj.pagination?.page || 1,
          size: dataObj.size || dataObj.pagination?.size || (params?.limit || 20)
        }
      }
      
      // 情况3: data.data是数组（嵌套）
      if (dataObj.data && Array.isArray(dataObj.data)) {
        return {
          items: dataObj.data,
          total: pagination?.total || dataObj.pagination?.total || dataObj.data.length,
          page: pagination?.page || dataObj.pagination?.page || 1,
          size: pagination?.size || dataObj.pagination?.size || (params?.limit || 20)
        }
      }
    }
    
    // 如果响应格式不符合预期，返回空数组
    console.warn('Unexpected requirement list response format:', response)
    return {
      items: [],
      total: 0,
      page: params?.skip ? Math.floor(params.skip / (params.limit || 20)) + 1 : 1,
      size: params?.limit || 20
    }
  },

  /**
   * 获取需求详情
   */
  async getRequirementById(id: string): Promise<RequirementResponse> {
    const apiResponse = await getRequirementById(id)
    if (apiResponse.success && apiResponse.data) {
      return apiResponse.data
    }
    throw new Error(apiResponse.message || '获取需求详情失败')
  },

  /**
   * 创建需求
   */
  async createRequirement(data: RequirementCreate): Promise<RequirementResponse> {
    const apiResponse = await createRequirement(data)
    if (apiResponse.success && apiResponse.data) {
      return apiResponse.data
    }
    throw new Error(apiResponse.message || '创建需求失败')
  },

  /**
   * 更新需求
   */
  async updateRequirement(id: string, data: RequirementUpdate): Promise<RequirementResponse> {
    const apiResponse = await updateRequirement(id, data)
    if (apiResponse.success && apiResponse.data) {
      return apiResponse.data
    }
    throw new Error(apiResponse.message || '更新需求失败')
  },

  /**
   * 删除需求
   */
  async deleteRequirement(id: string): Promise<void> {
    const apiResponse = await deleteRequirement(id)
    if (!apiResponse.success) {
      throw new Error(apiResponse.message || '删除需求失败')
    }
  },

  /**
   * 更新需求状态
   */
  async updateRequirementStatus(id: string, data: RequirementStatusUpdate): Promise<RequirementResponse> {
    const apiResponse = await updateRequirementStatus(id, data)
    if (apiResponse.success && apiResponse.data) {
      return apiResponse.data
    }
    throw new Error(apiResponse.message || '更新需求状态失败')
  },

  /**
   * 更新需求分配
   */
  async updateRequirementAssignee(id: string, data: RequirementAssignmentUpdate): Promise<RequirementResponse> {
    const apiResponse = await updateRequirementAssignee(id, data)
    if (apiResponse.success && apiResponse.data) {
      return apiResponse.data
    }
    throw new Error(apiResponse.message || '更新需求分配失败')
  }
}

// 默认导出
export default requirementAPI